/**
 * 前端版本管理器
 * 功能：检查应用版本变化，自动清理缓存并刷新页面
 * 版本策略：语义化版本号 (major.minor.patch)
 * 网络环境兼容：支持localhost和IP地址访问，防止跨域问题导致卡死
 */

import { getApiBaseUrlSync, getNodeApiUrlSync } from './apiConfig';

// 类型定义
type TranslationFunction = (key: string, params?: Record<string, any>) => string;

class FrontendVersionManager {
    // 当前应用版本号 - 每次发布时手动更新此版本号
    private readonly CURRENT_VERSION = '1.0.22';

    // localStorage中存储版本号的键名
    private readonly VERSION_STORAGE_KEY = 'app_cache_version';

    // 需要保留的关键数据键名（不会被清理）
    private readonly PRESERVE_KEYS = ['userData'];

    // 防止无限刷新的相关常量
    private readonly REFRESH_LOCK_KEY = 'app_refresh_lock';
    private readonly REFRESH_LOCK_TIMEOUT = 10000; // 10秒锁定时间
    private readonly MAX_REFRESH_ATTEMPTS = 3; // 最大刷新尝试次数
    private readonly REFRESH_ATTEMPTS_KEY = 'app_refresh_attempts';

    // 翻译函数，可选的，如果不提供则使用默认文本
    private t: TranslationFunction | null = null;

    /**
     * 设置翻译函数
     */
    setTranslationFunction(t: TranslationFunction): void {
        this.t = t;
    }

    /**
     * 获取翻译文本，如果翻译函数不可用则返回默认文本
     */
    private getText(key: string, params?: Record<string, any>, fallback?: string): string {
        if (this.t) {
            try {
                return this.t(key, params);
            } catch (error) {
                console.warn('Translation failed for key:', key, error);
            }
        }
        return fallback || key;
    }

    /**
     * 检查是否处于刷新锁定状态
     */
    private isRefreshLocked(): boolean {
        try {
            const lockTime = sessionStorage.getItem(this.REFRESH_LOCK_KEY);
            if (!lockTime) return false;

            const now = Date.now();
            const lockTimestamp = parseInt(lockTime, 10);

            // 如果锁定时间已过期，清除锁定
            if (now - lockTimestamp > this.REFRESH_LOCK_TIMEOUT) {
                sessionStorage.removeItem(this.REFRESH_LOCK_KEY);
                return false;
            }

            return true;
        } catch (error) {
            // console.warn('检查刷新锁定状态失败:', error);
            console.error('check refresh lock status failed', error);
            return false;
        }
    }

    /**
     * 设置刷新锁定
     */
    private setRefreshLock(): void {
        try {
            sessionStorage.setItem(this.REFRESH_LOCK_KEY, Date.now().toString());
        } catch (error) {
            // console.warn('设置刷新锁定失败:', error);
            console.error('set refresh lock failed', error);
        }
    }

    /**
     * 检查刷新尝试次数
     */
    private canAttemptRefresh(): boolean {
        try {
            const attemptsStr = sessionStorage.getItem(this.REFRESH_ATTEMPTS_KEY);
            const attempts = attemptsStr ? parseInt(attemptsStr, 10) : 0;
            return attempts < this.MAX_REFRESH_ATTEMPTS;
        } catch (error) {
            // console.warn('检查刷新尝试次数失败:', error);
            console.error('check refresh attempts failed', error);
            return true; // 出错时允许尝试
        }
    }

    /**
     * 增加刷新尝试次数
     */
    private incrementRefreshAttempts(): void {
        try {
            const attemptsStr = sessionStorage.getItem(this.REFRESH_ATTEMPTS_KEY);
            const attempts = attemptsStr ? parseInt(attemptsStr, 10) : 0;
            sessionStorage.setItem(this.REFRESH_ATTEMPTS_KEY, (attempts + 1).toString());
        } catch (error) {
            // console.warn('增加刷新尝试次数失败:', error);
            console.error('increment refresh attempts failed', error);
        }
    }

    /**
     * 清除刷新尝试计数
     */
    private clearRefreshAttempts(): void {
        try {
            sessionStorage.removeItem(this.REFRESH_ATTEMPTS_KEY);
        } catch (error) {
            // console.warn('清除刷新尝试计数失败:', error);
            console.error('clear refresh attempts failed', error);
        }
    }

    /**
     * 检测当前网络环境
     */
    private detectNetworkEnvironment(): {
        isNetworkAccess: boolean;
        hostname: string;
        shouldSkipNetworkChecks: boolean;
    } {
        const { hostname, protocol } = window.location;
        const isNetworkAccess = hostname !== 'localhost' && hostname !== '127.0.0.1';

        // 在IP地址访问时，可能存在跨域问题，应该跳过可能引起问题的网络检查
        const shouldSkipNetworkChecks = isNetworkAccess;

        // console.log('🌐 网络环境检测:', {
        //     hostname,
        //     protocol,
        //     isNetworkAccess,
        //     shouldSkipNetworkChecks
        // });

        return { isNetworkAccess, hostname, shouldSkipNetworkChecks };
    }

    /**
     * 检查版本并处理缓存
     * 在应用启动时调用
     */
    checkVersionAndManageCache(): {
        versionChanged: boolean;
        currentVersion: string;
        previousVersion?: string;
        action: 'none' | 'cache_cleared' | 'refresh_required' | 'blocked';
    } {
        try {
            // 检测网络环境
            const networkEnv = this.detectNetworkEnvironment();

            // 在网络环境下，如果可能存在跨域问题，采用更保守的策略
            if (networkEnv.shouldSkipNetworkChecks) {
                // console.log('🌐 检测到网络访问环境，采用网络兼容模式');

                // 获取本地存储的版本号
                const storedVersion = localStorage.getItem(this.VERSION_STORAGE_KEY);

                // 如果版本不一致，只清理缓存但不强制刷新页面
                if (!storedVersion || storedVersion !== this.CURRENT_VERSION) {
                    // console.log('🌐 网络环境下检测到版本变化，清理缓存但不强制刷新', {
                    //     stored: storedVersion,
                    //     current: this.CURRENT_VERSION
                    // });

                    // 清理缓存但保留关键数据
                    this.clearCacheOnly();

                    // 更新版本号
                    localStorage.setItem(this.VERSION_STORAGE_KEY, this.CURRENT_VERSION);

                    return {
                        versionChanged: true,
                        currentVersion: this.CURRENT_VERSION,
                        previousVersion: storedVersion || undefined,
                        action: 'cache_cleared'
                    };
                }

                // 版本一致，正常继续
                return {
                    versionChanged: false,
                    currentVersion: this.CURRENT_VERSION,
                    action: 'none'
                };
            }

            // console.log(this.getText('versionManager.logs.startVersionCheck', undefined, '🔍 开始前端版本检查...'));

            // 检查是否处于刷新锁定状态
            if (this.isRefreshLocked()) {
                // console.warn('⚠️ 检测到刷新锁定状态，跳过版本检查');
                console.error('detected refresh lock, skip version check');
                return {
                    versionChanged: false,
                    currentVersion: this.CURRENT_VERSION,
                    action: 'blocked'
                };
            }

            // 获取本地存储的版本号
            const storedVersion = localStorage.getItem(this.VERSION_STORAGE_KEY);

            // console.log(this.getText('versionManager.logs.versionComparison', undefined, '📊 版本对比:'), {
            //     current: this.CURRENT_VERSION,
            //     stored: storedVersion || 'none'
            // });

            // 首次访问或版本号不一致
            if (!storedVersion || storedVersion !== this.CURRENT_VERSION) {
                const isFirstVisit = !storedVersion;

                if (isFirstVisit) {
                    // console.log(this.getText('versionManager.logs.firstVisitInit', undefined, '🌟 首次访问，初始化版本号'));
                    // 首次访问，只保存版本号，不清理缓存
                    localStorage.setItem(this.VERSION_STORAGE_KEY, this.CURRENT_VERSION);

                    // 清除可能存在的刷新计数
                    this.clearRefreshAttempts();

                    return {
                        versionChanged: false,
                        currentVersion: this.CURRENT_VERSION,
                        action: 'none'
                    };
                } else {
                    // console.log(this.getText('versionManager.logs.versionChanged',
                    //     { oldVersion: storedVersion, newVersion: this.CURRENT_VERSION },
                    //     `🔄 检测到版本变化: ${storedVersion} → ${this.CURRENT_VERSION}`));

                    // 检查是否可以尝试刷新
                    if (!this.canAttemptRefresh()) {
                        // console.warn('⚠️ 刷新尝试次数已达上限，执行降级处理');
                        console.error('refresh attempts reached max, execute downgrade');
                        // 强制更新版本号，避免无限循环
                        localStorage.setItem(this.VERSION_STORAGE_KEY, this.CURRENT_VERSION);
                        // 清除刷新计数，重新开始
                        this.clearRefreshAttempts();
                        return {
                            versionChanged: true,
                            currentVersion: this.CURRENT_VERSION,
                            previousVersion: storedVersion,
                            action: 'cache_cleared'
                        };
                    }

                    // 版本变化，需要清理缓存
                    this.clearCacheAndRefresh();

                    return {
                        versionChanged: true,
                        currentVersion: this.CURRENT_VERSION,
                        previousVersion: storedVersion,
                        action: 'refresh_required'
                    };
                }
            } else {
                // console.log(this.getText('versionManager.logs.versionConsistent', undefined, '✅ 版本一致，无需清理缓存'));

                // 版本一致时清除刷新计数
                this.clearRefreshAttempts();

                return {
                    versionChanged: false,
                    currentVersion: this.CURRENT_VERSION,
                    previousVersion: storedVersion,
                    action: 'none'
                };
            }

        } catch (error) {
            console.error(this.getText('versionManager.logs.versionCheckError', undefined, '❌ 版本检查出错:'), error);

            // 出错时保守处理，不清理缓存，但确保版本号正确
            try {
                localStorage.setItem(this.VERSION_STORAGE_KEY, this.CURRENT_VERSION);
            } catch (e) {
                // console.error('❌ 保存版本号失败:', e);
                console.error('save version number failed', e);
            }

            return {
                versionChanged: false,
                currentVersion: this.CURRENT_VERSION,
                action: 'none'
            };
        }
    }

    /**
     * 仅清理缓存但不刷新页面（网络环境专用）
     */
    private clearCacheOnly(): void {
        try {
            // console.log('🧹 开始清理缓存（仅清理，不刷新）');

            // 获取所有localStorage的keys
            const keys = Object.keys(localStorage);
            // console.log('📋 当前localStorage包含的所有数据:', keys);

            // 保存需要保留的数据
            const preservedData: Record<string, string> = {};
            const preserveKeys = [...this.PRESERVE_KEYS, this.VERSION_STORAGE_KEY];

            preserveKeys.forEach(key => {
                const value = localStorage.getItem(key);
                if (value !== null) {
                    preservedData[key] = value;
                    // console.log(`💾 保留关键数据: ${key}`);
                }
            });

            // 清理localStorage（除了保留的数据）
            keys.forEach(key => {
                if (!preserveKeys.includes(key)) {
                    localStorage.removeItem(key);
                    // console.log(`🗑️ 清理缓存数据: ${key}`);
                }
            });

            // 恢复保留的数据
            Object.entries(preservedData).forEach(([key, value]) => {
                localStorage.setItem(key, value);
            });

            // console.log('✅ 缓存清理完成（网络环境模式）');

            // 🔧 修复：触发数据重新获取事件
            // 延迟触发，确保应用完全加载后再触发数据重新获取
            setTimeout(() => {
                try {
                    // console.log('🔄 网络环境模式：触发数据重新获取事件');
                    window.dispatchEvent(new CustomEvent('pageRefreshDataReload'));
                } catch (eventError) {
                    // console.warn('⚠️ 触发数据重新获取事件失败:', eventError);
                    console.warn('trigger data re-get event failed', eventError);
                }
            }, 100);

        } catch (error) {
            // console.error('❌ 缓存清理过程出错:', error);
            console.error('cache cleaning process failed', error);
        }
    }

    /**
     * 清理缓存并刷新页面
     */
    private clearCacheAndRefresh(): void {
        try {
            // console.log(this.getText('versionManager.logs.startClearCache', undefined, '🧹 开始清理缓存...'));

            // 设置刷新锁定，防止短时间内重复刷新
            this.setRefreshLock();

            // 增加刷新尝试次数
            this.incrementRefreshAttempts();

            // 1. 备份需要保留的数据
            const preservedData: Record<string, string> = {};
            this.PRESERVE_KEYS.forEach(key => {
                const data = localStorage.getItem(key);
                if (data) {
                    preservedData[key] = data;
                }
            });

            // console.log(this.getText('versionManager.logs.backupData', undefined, '💾 备份关键数据:'), Object.keys(preservedData));

            // 2. 清空所有localStorage数据
            localStorage.clear();

            // 3. 恢复保留的数据
            Object.entries(preservedData).forEach(([key, value]) => {
                localStorage.setItem(key, value);
            });

            // 4. 保存新版本号
            localStorage.setItem(this.VERSION_STORAGE_KEY, this.CURRENT_VERSION);

            // console.log(this.getText('versionManager.logs.clearCacheComplete', undefined, '✅ 缓存清理完成，准备刷新页面'));
            // console.log(this.getText('versionManager.logs.versionUpdate', undefined, '🔄 版本更新:'), this.CURRENT_VERSION);

            // 5. 显示更新提示（可选）
            this.showUpdateNotification();

            // 6. 延迟刷新，让用户看到提示，同时增加超时保护
            const refreshTimer = setTimeout(() => {
                try {
                    window.location.reload();
                } catch (error) {
                    // console.error('❌ 页面刷新失败:', error);
                    console.error('page refresh failed', error);
                    // 刷新失败时的降级处理
                    window.location.href = window.location.href;
                }
            }, 1000);

            // 超时保护：如果5秒后还没刷新，强制刷新
            setTimeout(() => {
                clearTimeout(refreshTimer);
                // console.warn('⚠️ 刷新超时，执行强制刷新');
                console.warn('refresh timeout, execute forced refresh');
                try {
                    window.location.href = window.location.href;
                } catch (error) {
                    // console.error('❌ 强制刷新失败:', error);
                    console.error('forced refresh failed', error);
                }
            }, 5000);

        } catch (error) {
            console.error(this.getText('versionManager.logs.clearCacheFailed', undefined, '❌ 清理缓存失败:'), error);

            // 即使清理失败，也尝试刷新页面，但要有超时保护
            try {
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } catch (refreshError) {
                // console.error('❌ 降级刷新也失败:', refreshError);
                console.error('downgrade refresh failed', refreshError);
                // 最后的降级方案：重定向到当前页面
                setTimeout(() => {
                    window.location.href = window.location.href;
                }, 2000);
            }
        }
    }

    /**
     * 显示版本更新提示
     */
    private showUpdateNotification(): void {
        // 获取翻译文本
        const updateTitle = this.getText('versionManager.ui.updateTitle', undefined, '🎉 Updata Now !');
        const refreshing = this.getText('versionManager.ui.refreshing', undefined, '');

        // 创建一个简单的提示框
        const notification = document.createElement('div');
        notification.innerHTML = `
      <div style="
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(0, 0, 0, 0.9);
        color: white;
        padding: 20px 30px;
        border-radius: 10px;
        font-size: 16px;
        z-index: 10000;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
        text-align: center;
        min-width: 300px;
      ">
        <div style="margin-bottom: 10px;">${updateTitle}</div>
        <div style="font-size: 14px; color: #ccc;">${refreshing}</div>
        <div style="
          width: 30px;
          height: 30px;
          border: 3px solid #333;
          border-top: 3px solid #fff;
          border-radius: 50%;
          animation: spin 1s linear infinite;
          margin: 15px auto 0;
        "></div>
      </div>
      <style>
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      </style>
    `;

        document.body.appendChild(notification);

        // 2秒后移除提示（实际上页面会在1秒后刷新）
        setTimeout(() => {
            if (document.body.contains(notification)) {
                document.body.removeChild(notification);
            }
        }, 2000);
    }

    /**
     * 获取当前版本号
     */
    getCurrentVersion(): string {
        return this.CURRENT_VERSION;
    }

    /**
     * 获取存储的版本号
     */
    getStoredVersion(): string | null {
        return localStorage.getItem(this.VERSION_STORAGE_KEY);
    }

    /**
     * 手动触发版本检查和缓存清理
     * 可用于开发调试或提供给用户的手动刷新功能
     */
    manualRefresh(): void {
        // console.log(this.getText('versionManager.logs.manualRefresh', undefined, '🔄 手动触发版本刷新'));
        this.clearCacheAndRefresh();
    }

    /**
     * 解析语义化版本号
     */
    private parseVersion(version: string): { major: number; minor: number; patch: number } {
        const parts = version.split('.').map(num => parseInt(num, 10));
        return {
            major: parts[0] || 0,
            minor: parts[1] || 0,
            patch: parts[2] || 0
        };
    }

    /**
     * 比较两个语义化版本号
     * 返回: 1 (v1 > v2), -1 (v1 < v2), 0 (相等)
     */
    compareVersions(v1: string, v2: string): number {
        const version1 = this.parseVersion(v1);
        const version2 = this.parseVersion(v2);

        if (version1.major !== version2.major) {
            return version1.major > version2.major ? 1 : -1;
        }

        if (version1.minor !== version2.minor) {
            return version1.minor > version2.minor ? 1 : -1;
        }

        if (version1.patch !== version2.patch) {
            return version1.patch > version2.patch ? 1 : -1;
        }

        return 0;
    }

    /**
     * 检查是否为重大版本更新（major版本变化）
     */
    isMajorUpdate(oldVersion: string, newVersion: string): boolean {
        const old = this.parseVersion(oldVersion);
        const current = this.parseVersion(newVersion);
        return current.major > old.major;
    }

    /**
     * 获取版本更新信息
     */
    getUpdateInfo(oldVersion?: string): {
        type: 'major' | 'minor' | 'patch' | 'none';
        description: string;
    } {
        if (!oldVersion) {
            return {
                type: 'none',
                description: this.getText('versionManager.updateTypes.none', undefined, '首次访问')
            };
        }

        const comparison = this.compareVersions(this.CURRENT_VERSION, oldVersion);

        if (comparison === 0) {
            return {
                type: 'none',
                description: this.getText('versionManager.updateTypes.same', undefined, '版本相同')
            };
        }

        const old = this.parseVersion(oldVersion);
        const current = this.parseVersion(this.CURRENT_VERSION);

        if (current.major > old.major) {
            return {
                type: 'major',
                description: this.getText('versionManager.updateTypes.major', undefined, '重大版本更新，包含新功能和重要改进')
            };
        }

        if (current.minor > old.minor) {
            return {
                type: 'minor',
                description: this.getText('versionManager.updateTypes.minor', undefined, '功能更新，新增特性和优化')
            };
        }

        if (current.patch > old.patch) {
            return {
                type: 'patch',
                description: this.getText('versionManager.updateTypes.patch', undefined, 'Bug修复和小幅优化')
            };
        }

        return {
            type: 'none',
            description: this.getText('versionManager.updateTypes.other', undefined, '版本回退或其他变化')
        };
    }
}

// 创建全局单例
export const frontendVersionManager = new FrontendVersionManager();

// 开发环境调试工具
if (import.meta.env.DEV) {
    (window as any).versionManager = {
        getCurrentVersion: () => frontendVersionManager.getCurrentVersion(),
        getStoredVersion: () => frontendVersionManager.getStoredVersion(),
        manualRefresh: () => frontendVersionManager.manualRefresh(),
        checkVersion: () => frontendVersionManager.checkVersionAndManageCache(),
        compareVersions: (v1: string, v2: string) => frontendVersionManager.compareVersions(v1, v2),

        // 测试功能：模拟版本变化
        simulateVersionChange: (fakeOldVersion: string) => {
            localStorage.setItem('app_cache_version', fakeOldVersion);
            // 使用翻译（如果可用）或默认文本
            const getText = (key: string, params?: Record<string, any>, fallback?: string) => {
                if ((frontendVersionManager as any).t) {
                    try {
                        return (frontendVersionManager as any).t(key, params);
                    } catch (error) {
                        return fallback || key;
                    }
                }
                return fallback || key;
            };

            // console.log(getText('versionManager.logs.setFakeVersion', { version: fakeOldVersion }, `已设置虚假版本: ${fakeOldVersion}`));
            // console.log(getText('versionManager.logs.testVersionUpdate', undefined, '刷新页面或调用 checkVersion() 来测试版本更新'));
        }
    };

    // 使用翻译（如果可用）或默认文本
    const getText = (key: string, params?: Record<string, any>, fallback?: string) => {
        if ((frontendVersionManager as any).t) {
            try {
                return (frontendVersionManager as any).t(key, params);
            } catch (error) {
                return fallback || key;
            }
        }
        return fallback || key;
    };

    // console.log(getText('versionManager.logs.debugToolsLoaded', undefined, '🛠️ 版本管理调试工具已加载'));
    // console.log(getText('versionManager.logs.debugToolsUsage', undefined, '使用 window.versionManager 访问调试功能'));
    // console.log(getText('versionManager.logs.currentVersion', undefined, '当前版本:'), frontendVersionManager.getCurrentVersion());
} 